package com.tianheng.wanzhou.datacollecting.netty.jiangsha;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.DataCollectingApplication;
import com.tianheng.wanzhou.datacollecting.db.entity.Jiangsha;
import com.tianheng.wanzhou.datacollecting.db.entity.JiangshaHis;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IJiangshaHisService;
import com.tianheng.wanzhou.datacollecting.db.service.IJiangshaService;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.enums.JiangShaEnum;
import com.tianheng.wanzhou.datacollecting.util.Data;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yujw
 * @Date: 2020/5/12 15:56
 * @Version 1.0
 */
@ChannelHandler.Sharable

@Component
@Slf4j


public class GatherServerHandler extends SimpleChannelInboundHandler {

    @Autowired
    IJiangshaService service;

    @Autowired
    IJiangshaHisService hisService;

    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;


    public static GatherServerHandler gatherServerHandler;


    @PostConstruct
    public void init() {
        gatherServerHandler = this;
        gatherServerHandler.service = this.service;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 1).eq("status", 1);
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void handlerAdded (ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        //打印出channel唯一值，asLongText方法是channel的id的全名
        log.info("新连接IP    ：" + clientIP + " ------新连接注册ID：" + ctx.channel().id().asLongText());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
        MachineList machine = new MachineList();
        for (MachineList machine1 : this.machineList) {
            if(clientIP.equals(machine1.getMacIp())){
                machine =machine1;
                break;
            }
        }
        Map<String, Data> dataMap = new HashMap<>();
        //接收数据
        ByteBuf byteBuf = (ByteBuf)msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String str = new String(bytes);
        //获取数据信息
        String message = str.split("\n\n")[1];
        //拆分数据
        String[] messages = message.split("&");
        for (String x : messages) {
            String[] current = x.split("=");
            Integer code = Integer.valueOf(current[0]);
            dataMap.put(JiangShaEnum.fromCode(code), new Data(current[1]));
        }
        dataMap.put("machineIp", new Data(machine.getMacIp()));
        dataMap.put("company", new Data(machine.getCompany()));
        dataMap.put("workshop", new Data(machine.getWorkshop()));
        dataMap.put("machineId", new Data(machine.getMacId()));
        Jiangsha jiangsha = (Jiangsha) Data.bind(new Jiangsha(), dataMap);
        service.saveOrUpdate(jiangsha);
        //存历史记录
        JiangshaHis lastRecord = DataCollectingApplication.jiangshaHis.get(clientIP);
        double now = Double.parseDouble(jiangsha.getActualYarnLength());
        double last = 0.00;
        if (null != lastRecord) {
            last = Double.parseDouble(lastRecord.getActualYarnLength());
        }
        JiangshaHis jiangshaHis = (JiangshaHis) Data.bind(new JiangshaHis(), dataMap);
        if ( now < last ){
            hisService.save(lastRecord);
            DataCollectingApplication.jiangshaHis.put(clientIP, jiangshaHis);
        } else {
            DataCollectingApplication.jiangshaHis.put(clientIP, jiangshaHis);
        }

    }



    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }


    @Override
    public void handlerRemoved (ChannelHandlerContext ctx) throws Exception {
        log.info("连接移除：" + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.getMessage());
        ctx.close();
    }
}
